/*
 * 入库管理控制器
 * 整合入库新增所需的所有API方法
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Core.Utilities;
using VOL.Core.Extensions.AutofacManager;

namespace VOL.demo.Controllers
{
    [Route("api/WarehousingManagement")]
    [ApiController]
    public class WarehousingManagementController : ControllerBase
    {
        private readonly IStockInOrderModelService _stockInOrderService;
        private readonly IStockInOrderItemModelService _stockInOrderItemService;
        private readonly IPurchaseOrderModelService _purchaseOrderService;
        private readonly IPurchaseOrderItemModelService _purchaseOrderItemService;
        private readonly IproductinformationmodelService _productService;
        private readonly IsuppliermodelService _supplierService;
        private readonly IwarehousemodelService _warehouseService;
        private readonly IstoragelocationmodelService _storageLocationService;
        private readonly IunitmodelService _unitService;
        private readonly ISys_UserService _userService;

        public WarehousingManagementController(
            IStockInOrderModelService stockInOrderService,
            IStockInOrderItemModelService stockInOrderItemService,
            IPurchaseOrderModelService purchaseOrderService,
            IPurchaseOrderItemModelService purchaseOrderItemService,
            IproductinformationmodelService productService,
            IsuppliermodelService supplierService,
            IwarehousemodelService warehouseService,
            IstoragelocationmodelService storageLocationService,
            IunitmodelService unitService,
            ISys_UserService userService)
        {
            _stockInOrderService = stockInOrderService;
            _stockInOrderItemService = stockInOrderItemService;
            _purchaseOrderService = purchaseOrderService;
            _purchaseOrderItemService = purchaseOrderItemService;
            _productService = productService;
            _supplierService = supplierService;
            _warehouseService = warehouseService;
            _storageLocationService = storageLocationService;
            _unitService = unitService;
            _userService = userService;
        }

        #region 入库单相关API

        /// <summary>
        /// 分页查询入库单
        /// </summary>
        [HttpGet("GetStockInOrderPageList")]
        public async Task<IActionResult> GetStockInOrderPageList(
            int pageIndex = 1,
            int pageSize = 10,
            string stockInCode = null,
            int? status = null,
            long? warehouseId = null,
            DateTime? stockInDate = null,
            long? inOutTypeId = null)
        {
            try
            {
                var result = await _stockInOrderService.GetStockInOrderPageListAsync(
                    pageIndex, pageSize, stockInCode, status, warehouseId, stockInDate, inOutTypeId);

                if (result.Status)
                {
                    return Ok(result);
                }
                else
                {
                    return Ok(new { success = false, message = result.Message });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据进货单号查询可入库的货品信息
        /// </summary>
        /// <param name="orderCode">进货单号</param>
        /// <returns>货品信息列表</returns>
        [HttpGet("GetPurchaseOrderGoods")]
        public async Task<IActionResult> GetPurchaseOrderGoods(string orderCode)
        {
            try
            {
                if (string.IsNullOrEmpty(orderCode))
                {
                    return Ok(new { success = false, message = "进货单号不能为空" });
                }

                // 获取进货单明细（调用带连表查询的方法，返回DTO，已包含unitName和realtimeInventory）
                var purchaseItems = await _purchaseOrderItemService.GetItemsWithJoinByOrderCodeAsync(orderCode);
                
                if (purchaseItems == null || purchaseItems.Count == 0)
                {
                    return Ok(new { success = false, message = "未找到进货单明细" });
                }

                // 从入库明细表统计该进货单已入库的数量
                // 查询所有关联该进货单号的入库单
                var stockInOrders = await _stockInOrderService.FindAsync(x => x.relatedOrderCode == orderCode && x.IsDel == 0);
                var stockInCodes = stockInOrders.Select(x => x.stockInCode).ToList();

                // 统计每个货品的已入库数量
                Dictionary<long, int> inStockedQuantities = new Dictionary<long, int>();
                
                if (stockInCodes.Count > 0)
                {
                    // 查询所有入库明细
                    var stockInItems = await _stockInOrderItemService.FindAsync(
                        x => stockInCodes.Contains(x.StockInCode) && x.IsDel == 0);
                    
                    // 按货品ID分组统计已入库数量
                    inStockedQuantities = stockInItems
                        .GroupBy(x => x.GoodsId)
                        .ToDictionary(
                            g => g.Key,
                            g => g.Sum(x => x.thisTimeQuantity ?? 0)
                        );
                }

                // 构造返回数据（只返回未完全入库的货品）
                var goodsItems = purchaseItems.Select(item => 
                {
                    int inStocked = inStockedQuantities.ContainsKey(item.GoodsId) 
                        ? inStockedQuantities[item.GoodsId] 
                        : 0;
                    int purchaseQty = item.PurchaseQty ?? 0;
                    int unStocked = purchaseQty - inStocked;

                    return new PurchaseOrderGoodsItemDto
                    {
                        GoodsId = item.GoodsId,
                        GoodsCode = item.GoodsCode,
                        GoodsName = item.GoodsName,
                        SpecModel = item.SpecModel,
                        UnitId = item.UnitId,
                        UnitName = item.UnitName,  // 从单位表连表查询获取
                        CurrentInventory = item.RealtimeInventory,  // 从货品信息表连表查询获取实时库存
                        PurchasePrice = item.PurchasePrice,
                        PurchaseQuantity = purchaseQty,
                        InStockedQuantity = inStocked,  // 实际已入库数量
                        UnStockedQuantity = unStocked,  // 实际未入库数量
                        Amount = item.PurchaseQty.HasValue && item.PurchasePrice.HasValue 
                            ? item.PurchaseQty.Value * item.PurchasePrice.Value 
                            : 0
                    };
                })
                .Where(x => x.UnStockedQuantity > 0)  // 过滤掉已完全入库的货品
                .ToList();
                
                return Ok(new { success = true, data = goodsItems, message = "查询成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 保存入库单
        /// </summary>
        /// <param name="request">入库单保存请求</param>
        /// <returns>保存结果</returns>
        [HttpPost("SaveStockInOrder")]
        public async Task<IActionResult> SaveStockInOrder([FromBody] SaveStockInOrderRequest request)
        {
            try
            {
                // 添加详细日志
                Console.WriteLine($"=== SaveStockInOrder 开始 ===");
                Console.WriteLine($"request is null: {request == null}");
                
                if (request == null)
                {
                    return Ok(new { success = false, message = "请求数据为空" });
                }
                
                Console.WriteLine($"request.StockInOrder is null: {request.StockInOrder == null}");
                Console.WriteLine($"request.OrderItems is null: {request.OrderItems == null}");
                Console.WriteLine($"request.OrderItems count: {request.OrderItems?.Count ?? 0}");
                
                if (request.StockInOrder == null)
                {
                    return Ok(new { success = false, message = "入库单信息不能为空" });
                }

                if (request.OrderItems == null || request.OrderItems.Count == 0)
                {
                    return Ok(new { success = false, message = "入库明细不能为空" });
                }

                // 生成入库单号
                if (string.IsNullOrEmpty(request.StockInOrder.stockInCode))
                {
                    request.StockInOrder.stockInCode = GenerateStockInCode();
                }

                // 使用事务保存主表和明细表
                var result = await _stockInOrderService.SaveStockInOrderWithItemsAsync(request);
                
                if (result.Status)
                {
                    return Ok(new { success = true, message = "保存成功", data = new { stockInCode = request.StockInOrder.stockInCode } });
                }
                else
                {
                    return Ok(new { success = false, message = result.Message });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = $"保存失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 生成入库单号
        /// </summary>
        private string GenerateStockInCode()
        {
            return $"SI{DateTime.Now:yyyyMMddHHmmss}";
        }

        #endregion
    }
}


